package kr.couponplay.android.activity.intro;

import java.util.ArrayList;
import java.util.List;

import kr.couponplay.android.Constants;
import kr.couponplay.android.activity.MainTabActivity;
import kr.couponplay.android.activity.R;
import kr.couponplay.android.activity.intro.command.AppInformationSettingCommand;
import kr.couponplay.android.activity.intro.command.Command;
import kr.couponplay.android.activity.intro.command.FileCacheSettingCommand;
import kr.couponplay.android.activity.intro.command.ShortcutAddCommand;
import kr.couponplay.android.activity.intro.command.SidSettingCommand;
import kr.couponplay.android.support.AlertUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;

@SuppressLint("HandlerLeak")
public class IntroActivity extends Activity {
	IntroActivity activity = this;

	private List<Command> commands = new ArrayList<Command>() {{
		add(new AppInformationSettingCommand());
		add(new FileCacheSettingCommand());
		add(new ShortcutAddCommand());
		add(new SidSettingCommand());
	}};

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.intro_activity);
        thread.start();
    }
	
    private Thread thread = new Thread(new Runnable() {
    	public void run() {
    		long startTime = System.currentTimeMillis();
    		Message msg = Message.obtain();
    		try {
	    		for (Command command : commands) {
		        	command.execute(activity);
		        }
    		} catch (Exception e) {
    			Log.e(Constants.TAG, e.getMessage(), e);
    			msg.obj = e;
    		}
    		long dulation = System.currentTimeMillis() - startTime;
    		handler.sendMessageDelayed(msg, (dulation < 2500)? 2500 - dulation : 0);
        }
    });	
	
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
			Exception exception = (Exception)msg.obj;
			if (exception == null) {
				finish();
		    	Intent intent = new Intent(activity, MainTabActivity.class);
				startActivity(intent);
			} else {
				alert(exception);
			}
        }
    };
    
    public void alert(Exception exception) {
        AlertUtils.errorAlert(this, exception);
    }
}
